python3.4学习笔记(二十一) python实现指定字符串补全空格、前面填充0的方法 您所在的位置:网站首页 python zfill函数 python3.4学习笔记(二十一) python实现指定字符串补全空格、前面填充0的方法

python3.4学习笔记(二十一) python实现指定字符串补全空格、前面填充0的方法

2023-03-14 22:17| 来源: 网络整理| 查看: 265

python3.4学习笔记(二十一) python实现指定字符串补全空格、前面填充0的方法

Python zfill()方法返回指定长度的字符串,原字符串右对齐,前面填充0。zfill()方法语法:str.zfill(width)参数width -- 指定字符串的长度。原字符串右对齐,前面填充0。返回指定长度的字符串。

以下实例展示了 zfill()函数的使用方法:#!/usr/bin/pythonstr = "this is string example....wow!!!";print str.zfill(40);print str.zfill(50);以上实例输出结果如下:00000000this is string example....wow!!!000000000000000000this is string example....wow!!!

zfill()则用于向数值的字符串表达式左侧填充0, 该函数可以正确理解正负号:>>> '12'.zfill(5)'00012’>>> '-3.14'.zfill(7)'-003.14'>>> '3.14159265359'.zfill(5)'3.14159265359'=====================================在Python中打印字符串时可以调用ljust(左对齐),rjust(右对齐),center(中间对齐)来输出整齐美观的字符串python实现指定字符串补全空格的方法:如果希望字符串的长度固定,给定的字符串又不够长度,我们可以通过rjust,ljust和center三个方法来给字符串补全空格rjust,向右对其,在左边补空格s = "123".rjust(5) assert s == " 123"

ljust,向左对其,在右边补空格s = "123".ljust(5) assert s == "123 "

center,让字符串居中,在左右补空格s = "123".center(5) assert s == " 123 "

 



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有